<template>
  <div class="engine-con">
    <div class="father head">
      <h2 class="title">{{ assemblyobj.name }}</h2>
    </div>
    <Engine
      :mode="MODE.PC"
      :scene="SCENE.PRODUCT"
      :dataInject="dataInject"
      :nodeInject="nodeInject"
      :bridge="bridge"
      @submit="onSubmit"
      ref="engine"
      class=""
    >
    </Engine>
    <div>
      <div class="nextstep-lc">
        <a-button type="primary" @click="onSubmits">确认流程</a-button>
      </div>
      <!-- 流程节点 -->
      <div class="father" style="margin-top: 20px" v-if="stepsshow">
        <div>
          <a-steps :current="0" direction="vertical">
            <a-step v-for="(item, index) in steps" :key="index" :title="item.nodeName" :description="getNodeDes(item)">
              <template slot="icon">
                <img v-if="item.nodeType === 'START'" src="./img/START.png" style="height: 30px; width: 30px" alt="" />
                <img
                  v-if="item.nodeType === 'APPROVER'"
                  src="./img/APPROVER.png"
                  style="height: 30px; width: 30px"
                  alt=""
                />
                <img
                  v-if="item.nodeType === 'NOTIFIER'"
                  src="./img/NOTIFIER.png"
                  style="height: 30px; width: 30px"
                  alt=""
                />
                <img
                  v-if="item.nodeType === 'SERVICE'"
                  src="./img/SERVICE.png"
                  style="height: 30px; width: 30px"
                  alt=""
                />
              </template>
            </a-step>
          </a-steps>
        </div>
        <div>
          <el-form :model="candidatesson">
            <el-form-item v-for="(item, index) in steps" :key="index" class="son">
              <!-- 结束节点不需要配置，不显示 -->
              <!-- <div v-if="index < steps.length - 1"> -->
              <!-- 默认值的情况 发起人/指定人员/发起人自己 -->
              <div v-if="getDefaultType(item)">
                <!-- <UserList :userList="selectUserList"></UserList> -->
                <!-- <a-textarea
                  :value="getTarget(item, index)"
                  :auto-size="{ minRows: 2, maxRows: 6 }"
                  disabled
                  getTargetArr(item, index)
                /> -->
                <a-input :value="getTarget(item, index)" disabled></a-input>
                <div
                  v-if="getTarget(item, index).length > 15"
                  class="look-all"
                  @click="lookAllUser(item, index)"
                >
                  <img src="./img/look-all.png" style="width: 100%" alt="查看全部" />
                </div>
              </div>
              <div v-else-if="item.approvalType == 'service'">
                 {{item.nodeName}}
              </div>
              <div v-else>
                <!-- 选择范围的人 -->
                <div v-if="selectType(item)">
                  <!-- <UserList :userList="processDataVo[index].selectUsers || []"></UserList>
                  <a-button @click="createBy(item, index)">选择</a-button> -->
                  <a-input-search
                    :value="getNameList(processDataVo[index].selectUsers || [])"
                    placeholder="请选择"
                    readOnly
                    unselectable="on"
                  >
                    <a-button slot="enterButton" @click.native="createBy(item, index)">选择</a-button>
                  </a-input-search>
                </div>
                <!-- 选择所有人 -->
                <div v-else>
                  <!-- <UserList :userList="processDataVo[index].selectUsers || []"></UserList> -->
                  <!-- <a-button @click="createBy(item, index)">选择</a-button> -->
                  <j-select-user-by-dep
                    :modalWidth="900"
                    :userIndex="index"
                    :multi="item.properties.actionerRules[0].multi"
                    v-model="processDataVo[index].selectUserName"
                    @changeRow="onChangeUserName"
                  ></j-select-user-by-dep>
                </div>
                <!-- </div> -->
              </div>
            </el-form-item>
          </el-form>
          <el-dialog title="选择审批人" :visible.sync="dialogFormVisible" width="25%">
            <el-select v-model="region" :multiple="multiples" placeholder="请选择">
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="item.realname || item.realName"
                :value="item.id || item.userId"
              ></el-option>
            </el-select>
            <div slot="footer" class="dialog-footer">
              <a-button @click="dialogFormVisible = false" style="margin-right: 15px">取 消</a-button>
              <a-button type="primary" @click="primary()">确 定</a-button>
            </div>
          </el-dialog>
          <!-- roleListShow -->
        </div>
      </div>
      <!-- 流程节点结束 -->
      <div class="ra-save" v-if="stepsshow">
        <a-button style="margin-right: 15px" @click="$router.back(-1)">取消</a-button>
        <a-button type="primary" :loading="onSubmitLoading" :disabled="!stepsshow" @click="onSubmitend()"
          >提交</a-button
        >
      </div>
    </div>
    <!-- 所有用户 -->
    <a-modal v-model="showAllUser" title="查看全部" @ok="handleOk">
      <a-table :scroll="{ y: 300 }" :columns="columns" :data-source="allUser" bordered :pagination="false">
        <div slot="name" slot-scope="text, record">{{ record.realName || record.realname }}</div>
      </a-table>
      <!-- <p v-for="item in allUser" :key="item.id">{{ item.realName || item.realname }}</p> -->
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: '序号',
    dataIndex: '',
    key: 'rowIndex',
    width: 100,
    align: 'center',
    customRender: function (t, r, index) {
      return parseInt(index) + 1
    },
  },
  {
    dataIndex: 'realname',
    key: 'realname',
    title: '用户姓名',
    scopedSlots: { customRender: 'name' },
  },
  // {
  //   title: '用户账号',
  //   dataIndex: 'username',
  //   key: 'username',
  // },
]
import OA, {
  Engine,
  MODE,
  SCENE,
  Bridge,
  injectRequest,
  provideRequest,
  NodeStore,
  convert,
} from '@/components/oa/oa-process.umd'
import { post, get, put } from '@/api/request'
import moment from 'moment'
import '@/components/oa/oa-process.css'
import UserList from './userList'
import { getAssembles, getPreviewProcess, saveProcessStart, getSelectListByIds, getRoleNotContainsMe } from '@/api/api'
const bridge = new Bridge()
// import { canLinkNode } from '@/utils'
import componentLinkage from '@/utils/ComponentLinkage'
export default {
  components: {
    Engine,
    OA,
    UserList,
  },
  inject: ['closeCurrent'],
  data() {
    return {
      columns,
      assemblyobj: {
        name: '',
      },
      allUser: [],
      showAllUser: false,
      onSubmitLoading: false,
      roleListShow: false, //角色下用户列表
      allUserList: [], //所有固定选择的用户列表
      userNameList: [], //选择的用户的列表
      userList: {},
      defaultType: ['START', 'target_originator', 'target_approval', 'target_role', 'target_management'],
      disableds: false,
      flag: 0,
      stepsshow: false,
      dialogFormVisible: false,
      multiples: true, //流程审批人是否开启多选
      MODE,
      SCENE,
      processDataVoId: '', //流程code
      candidatesson: {},
      region: [], //已选审批人
      memberList: [], //流程审批人列表
      procFormDatas: [], //表单数据
      processDataVo: [], //流程提交列表
      steps: [], //流程步骤条
      stepsList: { START: '发起人', APPROVER: '审批人', END: '结束节点', NOTIFIER: '抄送人' }, //流程类型映射
      // stepsList: { START: '发起人', APPROVER: '审批人', END: '结束节点' }, //流程类型下的分类映射
      approvalTypeList: {
        target_select: '发起人自选',
        START: '发起人自选',
        target_originator: '发起人自己',
        target_approval: '指定人员',
        target_role: '角色',
        target_management: '部门',
      }, //流程类型的属性映射
      nodeInject: new NodeStore(),
      bridge,
      nodeSort: '', //下标
      dataInject: {
        getCanvas: () => {
          return this.procFormInfoqueryByIds()
        },
      },
      // id:''
    }
  },
  created() {
    this.browserRedirect()
    injectRequest({ post, get, put })
    window.test = this
  },
  computed: {
    id() {
      return this.$route.query.id
    },
  },
  mounted() {
    //监听节点变化
    this.procFormInfoqueryByIds()
    var that = this
    bridge.addEventListener('nodes', (nodes) => {
      that.stepsshow = false
      that.processDataVo = []
    })

    // console.log(that.$refs.engine, 'that.$refs.engine')
  },
  watch: {
    $route(to, from) {
      this.procFormInfoqueryByIds()
    },
  },
  destroyed() {},
  methods: {
    browserRedirect() {
      var sUserAgent = navigator.userAgent.toLowerCase()
      if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
        //跳转移动端页面
        console.log('跳转移动端页面')
        // this.$router.push('/mobileapplyFormDetails')
        this.$router.push({
          path: '/mobileapplyForm',
          query: { id: this.$route.query.id, fullName: this.$route.query.fullName,formType:this.$route.query.formType },
        })

        //
      } else {
        //跳转pc端页面
        // this.$router.push('/applyFormDetails')
        // this.$router.push({
        //   path: '/applyForm',
        //   // query: { processInstanceId: this.$route.query.processInstanceId, title: this.$route.query.title },
        // })

        console.log('跳转pc端页面')
      }
    },
    lookAllUser(item) {
      if (item.approvalType === 'target_approval') {
        const { approvals } = item.properties.actionerRules[0]
        const list = this.getIdUser(approvals)
        this.showAllUser = true
        this.allUser = list
      }
      this.showAllUser = true
      this.allUser = item.operatorList
    },
    handleOk() {
      this.showAllUser = false
    },
    //精简用户列表数组传输
    getUserListSimple(arr) {
      if (arr.length > 0) {
        const list = arr.map((item) => {
          return {
            realName: item.realname || item.realName,
            userId: item.id || item.userId,
            // username: item.username,
          }
        })
        return list
      } else {
        return []
      }
    },
    // 获取用户ID
    getUserIdList(array) {
      let list = []
      array.forEach((i) => {
        if (i.approvalType === 'target_select') {
          const approvals = i.properties.actionerRules ? i.properties.actionerRules[0].select[0] : ''
          if (approvals === 'approvals') {
            list = list.concat(i.properties.actionerRules[0].range.approvals)
          }
        }
        if (i.approvalType === 'target_approval') {
          list = list.concat(i.properties.actionerRules[0].approvals)
        }
      })
      return list
    },
    onChangeUserName(e, arr, index) {
      this.processDataVo[index].selectUsers = this.getUserListSimple(arr)
    },
    getUserName(item) {
      // console.log(this.getNameList(item.selectUsers || []), '选中的人')
      return this.getNameList(item.selectUsers || [])
    },
    getNodeDes(item) {
      const rangeSelect = {
        labels: '角色',
        approvals: '指定成员',
        allStaff: '全公司',
      }
      if (item.nodeType === 'APPROVER') {
        const num = item.selectUsers ? item.selectUsers.length + '人' : ''
        return num ? num + '审批' : '请选择审批人'
      }
      if (item.nodeType === 'NOTIFIER') {
        const type = rangeSelect[item.approvalType]
        const num = item.selectUsers ? item.selectUsers.length + '人' : ''
        return '抄送人' + num
      }
      return item.nodeType !== 'END' ? this.stepsList[item.nodeType] : ''
    },
    onSubmitend() {
      const formId = this.$route.query.id
      const formType = this.$route.query.formType
      const procFormDatas = this.procFormDatas
      const processDataVoList = this.processDataVo
      let proObj = {
        formId,
        procFormDatas,
        formType,
        processDataVo: {
          processCode: this.processDataVoId,
          formId: formId,
          nodeDtos: processDataVoList,
        },
      }

      const isproNo = processDataVoList.filter((item) => {
        if(item.nodeType == 'SERVICE'){
          return false;
        }
        return item.nodeType !== 'END' ? !item.selectUsers || item.selectUsers.length <= 0 : false
      })
      
      if (isproNo && isproNo.length > 0) {
        this.$message.error('节点信息必填')
        return
      }
      this.onSubmitLoading = true

      console.log(proObj,'proObj')

      saveProcessStart(proObj).then((res) => {
        if (res.code === 200) {
          this.onSubmitLoading = false
          setTimeout(() => {
            this.$router.push('/process/approval/MyTaskNeedToExcute')
          }, 100)
          this.closeCurrent()
        } else {
          this.onSubmitLoading = false
          this.$message.error('提交失败')
        }
      }).catch((e) => {
        this.onSubmitLoading = false
        console.log(e,'eeeee')
      })
    },
    getUserIdSelectlist(arr) {
      // console.log(arr, '1')
      getSelectListByIds({ ids: arr.toString() }).then((res) => {
        this.allUserList = res.result
      })
    },
    //根据多个id匹配找用户信息列表
    getIdUser(arr) {
      const list = this.allUserList.filter((item) => {
        return arr.includes(item.id)
      })
      return list
    },
    getPreviewProcessData(arr) {

    
      getPreviewProcess({ formId: this.$route.query.id,procFormDatas:arr}).then((res) => {
        if (res.success) {
          this.stepsshow = true
          let nodeDtosArr = res.result.nodeDtos.filter((item) => item.nodeType != "SERVICE")
          

          this.processDataVoId = res.result.processCode
          this.processDataVo = nodeDtosArr;
          let newpro = this.processDataVo.map((item) => {
            if (this.defaultType.includes(item.approvalType)) {
              item.selectUsers = item.operatorList
            }
          })
         
         this.steps = nodeDtosArr;
          console.log(newpro, 'this.processDataVo')
          // this.steps = res.result.nodeDtos;
          // console.log(res.result.nodeDtos,'res.result.nodeDtos')
          const list = [...nodeDtosArr]
          this.getUserIdSelectlist(this.getUserIdList(list))
        } else {
          this.$message.error(res.message)
          // this.$message({
          //   showClose: true,
          //   message: res.message,
          //   type: 'info',
          // })
        }
      })
    },
    //是为默认显示的值
    getDefaultType(item) {
      console.log(item,this.defaultType,'this.defaultType')
      return this.defaultType.includes(item.approvalType)
    },
    //范围是否是全公司
    selectType(e) {
      // console.log(e,'范围是否是全公司')
      if (e.properties.actionerRules[0].select && e.properties.actionerRules[0].select[0] !== 'allStaff') {
        return true
      }
      return false
    },
    // 确定范围成员
    primary() {
      let selectList = this.memberList
        .map((item) => {
          const id = item.id || item.userId
          return this.region.includes(id) ? item : ''
        })
        .filter((item) => {
          return item !== ''
        })
      console.log(selectList, 'selectList', this.region, this.memberList)
      console.log(this.getUserListSimple(selectList), 'this.getUserListSimple(selectList)')
      this.processDataVo[this.nodeSort].selectUsers = this.getUserListSimple(selectList)
      this.region = ''
      this.dialogFormVisible = false
    },
    // 回显默认值数组
    getTargetArr(item, index) {
      console.log(item.operatorList,'item.operatorList')
      if (item.approvalType === 'target_approval') {
        const { approvals } = item.properties.actionerRules[0]
        const list = this.getIdUser(approvals)
        return list
      }
      console.log(item.operatorList,'item.operatorList')
      return item.operatorList
    },
    // 回显默认值
    getTarget(item, index) {
      if (item.approvalType === 'target_approval') {
        const { approvals } = item.properties.actionerRules[0]
        const list = this.getIdUser(approvals)
        // this.processDataVo[index].selectUsers = list
        return this.getNameList(list)
      }
      // this.processDataVo[index].selectUsers = this.getUserListSimple(item.operatorList)
      return this.getNameList(item.operatorList)
    },
    getNameList(arr) {
      if (arr.length > 0) {
        let name = arr.map((item, index) => {
          return item.realName || item.realname
        })
        // console.log(name, 'name')
        return name.toString()
      }
      return ''
    },
    createBy(item, index) {
      const actionerRules = item.properties.actionerRules[0]
      const selectType = actionerRules.select[0]
      this.region = null
      this.dialogFormVisible = true
      if (selectType === 'labels') {
        getRoleNotContainsMe({
          roleId: item.properties.actionerRules[0].range.role[0].roleId,
          userKey: this.steps[0].operatorList[0].userId,
        }).then((res) => {
          this.memberList = res.result
          this.multiples = actionerRules.multi
        })
        this.nodeSort = index
        return
      }
      this.memberList = selectType === 'approvals' ? this.getIdUser(actionerRules.range.approvals) : []
      this.multiples = actionerRules.multi
      this.nodeSort = index
    },
    onSubmit() {
      // console.log(this.$refs.engine.resetFields(),'SS')
    },

    onSubmits() {
  
      const nodes = bridge.getDataSource('nodes')
      console.log(nodes, 'nodesssss+++')
      var node = convert.out(nodes)
      console.log(node, 'node+++')

      // console.log(node, 'node2')
      var list = []
      var procFormDatas = []
      componentLinkage.updateInfo(node)
      for (let i = 0; i < node.length; i++) {
        var colName = node[i].props.colName
        var value = node[i].value
        var required = node[i].isRequired
        var type = node[i].type
        var nid = node[i].nid
        if (required == '1' && componentLinkage.isNodeVisible({ nodes: node, id: node[i].nid })) {
          var map = {}
          // map[nid] = value
          map.key = nid
          map.value = value
          map.nid = nid
          map.colName = colName
          list.push(map)
          if (value == '' || value == null || value == undefined) {
            return this.$message.error('必填项不能为空')
          }
        }
        var maps = {}
        // maps[nid] = value
        maps.key = nid
        maps.value = value
        maps.colName = colName
        maps.nid = nid
        procFormDatas.push(maps)
        // }
      }
      
      
      let procFormDatasArr = nodes.map((item) => {
         return {
           colName:item.props.colName,
           value:item.value
         }
      })

      console.log(nodes,procFormDatasArr,'nodes')
      this.getPreviewProcessData(procFormDatasArr)

      this.procFormDatas = procFormDatas
      console.log(this.procFormDatas, 'procFormDatas')
    },
    // 自定义表单-通过id查询
    procFormInfoqueryByIds() {
      var id = this.$route.query.id
      let par = {
        id: id,
      }
      return getAssembles(par)
        .then((res) => {
          this.assemblyobj = res.result
          res.result.assemblyList.forEach((item) => {
            delete item.value
          })
          return res.result.assemblyList
        })
        .catch((e) => {
          this.formshow = false
        })
    },
    onSuccess(v,e) {

      console.log(v,e,'w')
      if (v === '成功') {
        this.$router.push({ path: '/OAwork/Approval/Processtemplate' })
      }else{
        this.$message.error(v)
      }
    },
    clear() {
      try {
        this.$refs.oa.$refs.info.resetForm()
      } catch (e) {
        //
      }
    },
  },
}
</script>
<style>
.engine-con .layout-node {
  min-height: 100px !important;
  height: 100%;
  overflow: auto;
}
.ant-steps-dot .ant-steps-item-content,
.ant-steps-dot.ant-steps-small .ant-steps-item-content {
  width: 568px;
}
</style>
<style scoped>
.head {
  justify-content: left !important;
  padding-left: 40px !important ;
  border-bottom: 1px dashed #ebebeb;
}

.look-all {
  position: absolute;
  right: -30px;
  top: -2px;
  height: 27px;
  width: 27px;
}
.look-all:hover {
  cursor: pointer;
  /* background; */
}
.ant-steps-vertical .ant-steps-item-description {
  /* padding-bottom: 35px; */
}
/* .el-form-item {
  margin-bottom: 15px;
} */
.father {
  background: #fff;
  /* border-radius: 10px; */
  padding: 20px 0 20px 0;
  width: 1000px;
  margin: 0px auto;
  display: flex;
  justify-content: space-around;
}
.oa-container {
  background: #fff;
}
.engine-con .layout {
  min-height: 100px !important;
  /* min-height: 50px !important; */
}
.engine {
  overflow: auto;
}
.engine-con {
  /* padding: 24px; */
  width: 1000px;
  margin: 0 auto;
  /* border-radius: 15 px; */
}
.nextstep-lc {
  text-align: center;
  width: 1000px;
  margin: 0 auto;
  padding-bottom: 15px;
  background: #fff;
}
.ra-save {
  text-align: center;
  /* padding:20px; */
  margin-top: 20px;
}
</style>